package dao;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import domain.Item;
import domain.Topic;
import domain.User;

public class TopicDaoImpl implements TopicDao {
	private SessionFactory sessionFactory;
	private AdminDao adminDao;
	
	
	


	public AdminDao getAdminDao() {
		return adminDao;
	}

	public void setAdminDao(AdminDao adminDao) {
		this.adminDao = adminDao;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public void insertTopic(String content, int item_id, String acc) {
		List list = adminDao.getUserByAccount(acc);
		Session session = sessionFactory.getCurrentSession();
		Item item = (Item) session.get(Item.class, item_id);
		Topic topic = new Topic();
		topic.setPost_time(new Date());
		topic.setContent(content);
		User u = null;
		if(list.size()>0)
			u = (User) list.get(0);
		item.getTopics().add(topic);
		session.saveOrUpdate(item);
		topic.setPost_user(u);
		session.saveOrUpdate(topic);
		
		
	}
	@Override
	public List<Topic> showTopic(int item_id){
		Session session = sessionFactory.getCurrentSession();
		Query q = session.createQuery("from Item where item_id = ?");
		q.setInteger(0, item_id);
		List <Item>list = q.list();
		Item item = null;
		if(list.size()>0){
			item = list.get(0);
		}
		List<Topic> topics = item.getTopics();
		Iterator<Topic> it = topics.iterator();
		while(it.hasNext()){
			System.out.println(it.next().getPost_user().getName());
		}
		return topics;
	}
}
